<template>
  <div class="article-manage_page">
       <List  item-layout="vertical" :border='true'>
        <ListItem v-for="(item,index) in data" :key="item.index">
          {{item.contentTitle}}
            <ListItemMeta  :description="`作者:${item.email}   日期:${item.created_time}`"/>
            <template slot="action">
                <li>
                    <a  @click.prevent="edt(index)">编辑</a>
                </li>
                <li>
                    <a  @click.prevent="del(index)">删除</a>
                </li>
                 <li v-if="item.check == 0">
                    <a  @click.prevent="check(index)">审核中</a>
                </li>
                <li v-else>
                    <a  @click.prevent="check(index)">已审核</a>
                </li>
            </template>
        </ListItem>
    </List>
    <Page :total="total" show-total @on-change='currentPage' style="margin-top:6px" :page-size='limit'/>
    <Modal
        v-model="modal"
        title="删除文章"
        :loading="loading"
        @on-ok="asyncOK()">
        <div v-html="content"></div>
    </Modal>
     <div>
        <Drawer
            title="文章修改"
            v-model="value3"
            width="720"
            :mask-closable="false"
            :styles="styles"
        >
           <Form :model="articleForm" :label-width="80" :rules="ruleInline" ref="articleForm">
          <FormItem label="文章标题" prop='contentTitle'>
              <Input v-model="articleForm.contentTitle" placeholder="Enter something..."></Input>
          </FormItem>
          <FormItem label="分类专栏" prop='lanmu' style="width:200px;display:inline-block;margin-right:60px;">
              <Select v-model="articleForm.lanmu">
                  <Option value="0">技术杂谈</Option>
                  <Option value="1">生活随笔</Option>
              </Select>
          </FormItem>
           <FormItem label="文章类别" prop='classify' style="width:200px;display:inline-block">
              <Select v-model="articleForm.classify">
                  <Option value="0">原创</Option>
                  <Option value="1">转载</Option>
                  <Option value="2">翻译</Option>
              </Select>
          </FormItem>
          <FormItem label="发布日期" style="width:400px">
              <Row>
                  <Col span="11">
                      <DatePicker type="date" placeholder="Select date" v-model="articleForm.date" @on-change="date"></DatePicker>
                  </Col>
                  <Col span="2" style="text-align: center">-</Col>
                  <Col span="11">
                      <TimePicker type="time" placeholder="Select time" v-model="articleForm.time"></TimePicker>
                  </Col>
              </Row>
          </FormItem>
          <FormItem label="文章标签" prop='tag'>
            <Input v-model="articleForm.tag" placeholder="Enter something..." ></Input>
          </FormItem>
          <FormItem :label-width="0" prop='content'> 
               <div class="edit_container">
                    <quill-editor 
                    v-model="articleForm.content"
                    ref="myQuillEditor"
                    style="height:300px;"
                    :options="editorOption">
                    </quill-editor>
                </div> 
                <Upload
                    multiple
                    ref="upload"
                    :format="['jpg','jpeg','png']"
                    :max-size="5120"
                    accept="image/*"
                    action="//jsonplaceholder.typicode.com/posts/">
                    <Button style="display:none" id="picFile"></Button>
                </Upload>              

          </FormItem>
          <FormItem>
              <Button style="margin-left: 8px;display:none" >Cancel</Button>
          </FormItem>
      </Form>
            <div class="demo-drawer-footer">
                <Button style="margin-right: 8px" @click="value3 = false">Cancel</Button>
                <Button type="primary" @click="handleSubmit1('articleForm')">Submit</Button>
            </div>
        </Drawer>    
    </div>
  </div>
</template>

<script>
export default {
   data () {
      return {
         articleForm: {
            contentTitle: '',
            lanmu: '',
            classify: '',
            date: '',
            time: '',
            content: ``,
            _id:'',
            contentUrl:'',
            tag:'无',
        },
        ruleInline: {
            contentTitle: [
                { required: true, message: 'Please fill in the title', trigger: 'blur',max:30},
                // {type:String,max:100, message: 'Length to long', trigger: 'blur'}
            ],
            lanmu: [
                { required: true, message: 'Please fill in the value', trigger: 'blur'}
            ],
            classify: [
                { required: true, message: 'Please fill in the value.', trigger: 'blur' }
            ],
            content: [
                { required: true, message: 'Please fill in the content.', trigger: 'blur' }
            ],
            tag: [
                { required: true, message: 'Please fill in the tag.', trigger: 'blur' },
                {max:5,message: 'too long.', trigger: 'blur' }
            ]
        },
        ischecked:[],
        addTagName:'',
        addTag: [],
        existTag:[],
        imgName: '',
        visible: false,
        uploadList: [],
        editorOption: {
          
        },
        value3: false,
        styles: {
            height: 'calc(100% - 55px)',
            overflow: 'auto',
            paddingBottom: '53px',
            position: 'static'
        },
        data: [],
        current:0,//当前页数
        limit:5,//每页的数据
        total:10,//总数
        content:'',
        loading: true,
        index:1,
        modal:false,
       
      

      }
  },
  computed: {
      editor() {
          return this.$refs.myQuillEditor.quill;
      },
  },
  methods:{
     date(v1){
          this.articleForm.date = v1                
      },
    init(){
      const that = this
      this.$axios.get('/api/manage/article/get',{params:{page:this.current,limit:this.limit}}).then(res =>{
        that.data = res.data.data
        that.total = res.data.total
      })
    },
    currentPage(page){
      this.current = page-1;
      this.init()
    },
    //触发事件
    del(index){
      this.index =index
      this.modal = true;
      this.content = `${this.data[index].contentTitle}<br><p style="color:red">确认要删除该文章？</p>`
    },
    edt(index){
      this.index = index
      this.articleForm.contentTitle = this.data[index].contentTitle
      this.articleForm._id = this.data[index]._id
      this.articleForm.tag = this.data[index].tag
      this.articleForm.contentUrl = this.data[index].contentUrl
      this.articleForm.lanmu = this.data[index].lanmu.toString()
      this.articleForm.classify = this.data[index].classify.toString()
      this.articleForm.date = this.data[index].created_time.slice(0,10)
      this.articleForm.date =  new Date(this.articleForm.date).toISOString().replace(/T/g, " ").replace(/\.[\d]{3}Z/, "")
      this.articleForm.time = this.data[index].created_time.slice(10)
      let that = this
      this.$axios.get('/api/manage/article/getByUrl',{params:{contentUrl:this.data[index].contentUrl}}).then(res =>{
        that.articleForm.content = res.data.data
        that.value3 = true
      })
      
    },
    //删除文章
    asyncOK(){
        const that = this
        this.$axios.post('/api/manage/article/del',{_id:this.data[this.index]._id,contentUrl:this.data[this.index].contentUrl}).then(res =>{
          // console.log(res);
          setTimeout(() => {
              this.modal = false;
          }, 500);
          if(res.data.err_code == 2){
              that.$Message.error('权限不足！');
          }else if(res.data.err_code == 1){
              that.$Message.error('你好像被开除了！');
          }else if(res.data.err_code == 0){
              that.$router.push('/login')
          }else if(res.data.err_code == 3){
              that.$Message.success('文章删除成功！');
              that.data.splice(that.index, 1);
          }else{
              that.$Message.error('文章删除失败！')
          }
        })
    },
    //修改文章
     handleSubmit1 (name) {
          this.$refs[name].validate((valid) => {
              if (valid) {
                    const that = this
                    this.$axios.post('/api/manage/article/edt',this.articleForm).then(res =>{
                      if(res.data.err_code == 0){
                        that.$router.push('/login')
                      }else if(res.data.err_code == 1){
                        that.$Message.error('没查询到用户！')
                      }else if(res.data.err_code == 2){
                        that.$Message.error('权限不足！')
                      }else if(res.data.err_code == 3){
                        that.$Message.success('文章修改成功！')
                        that.value3 = false
                        that.init()
                      }else if(res.data.err_code == 4){
                        that.$Message.error('参数有误！')
                      }else{
                        that.$Message.error('服务器出错！')
                      }
                    })
              } else {
                  this.$Message.error('Fail!');
              }
          })
      },
      //审核文章变更
      check(index){
        let that = this
        this.$axios.post('/api/manage/article/checkToChange',{_id:this.data[index]._id}).then(res =>{
          if(res.data.err_code == 0){
              that.$router.push('/login')
            }else if(res.data.err_code == 1){
              that.$Message.error('没查询到用户！')
            }else if(res.data.err_code == 2){
              that.$Message.error('权限不足！')
            }else if(res.data.err_code == 3){
              that.$Message.success('变更成功！')
              that.init()
            }else{
              that.$Message.error('服务器出错！')
            }

        })
      }
  },
  mounted(){
    this.init()
     var vm =this
      var imgHandler = async function(image) {
      vm.addImgRange = vm.$refs.myQuillEditor.quill.getSelection()
      if (image) {
          var fileInput = document.getElementById('picFile') //隐藏的file文本ID
          fileInput.click() //加一个触发事件
      }
      }
      vm.$refs.myQuillEditor.quill.getModule("toolbar").addHandler("image", imgHandler)
}
}
</script>

<style scoped>
  .ivu-modal-body textarea{
    border: none;
    outline: none
  }
</style>